package com.hxb.ruifeng.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hxb.ruifeng.entity.CodeMsg;
import com.hxb.ruifeng.entity.Result;
import com.hxb.ruifeng.entity.User;
import com.hxb.ruifeng.entity.enums.RedisKeyEnum;
import com.hxb.ruifeng.entity.vo.LoginVo;
import com.hxb.ruifeng.entity.vo.UserVo;
import com.hxb.ruifeng.entity.vo.UserVo2;
import com.hxb.ruifeng.mapper.UserMapper;
import com.hxb.ruifeng.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxb.ruifeng.util.DigestUtil;
import com.hxb.ruifeng.util.JsonUtil;
import com.hxb.ruifeng.util.JwtTokenUtil;
import com.hxb.ruifeng.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HXB
 * @since 2024-01-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Autowired
    private RedisUtil redisUtil;
    @Override
    public Result<?> loginUser(LoginVo loginVo) {
        //根据用户名查找用户
        User user =
                userMapper.selectOne(
                        Wrappers.<User>lambdaQuery()
                                .eq(User::getUsername, loginVo.getUsername()));
        //如果为空，返回用户不存在
        if (user == null) {
            return new Result<>(CodeMsg.USER_NOT_EXIST);
        } else {
            //存在则验证密码
            String password = DigestUtil.sha256Digest(loginVo.getPassword());  //加密的密码
            //密码验证不通过，然会密码错误信息
            if (!user.getPassword().equals(password)) {
                return new Result<>(CodeMsg.USER_PASS_ERROR);
            }
            //生成一个不带‘ - ‘的uuid，用来和jwt一起存进redis
            String redisUserKey = UUID.randomUUID().toString().replaceAll("-", "");

            //创建要返回的对象
            UserVo userDto = new UserVo();
            userDto.setId(user.getId()).setToken(redisUserKey);

            //转为json字符串
            String jsonStr = JsonUtil.beanToJson(userDto);

            //生成随机数  增强安全性
            final String randomKey = jwtTokenUtil.getRandomKey();
            //生成token
            final String token = jwtTokenUtil.generateToken(jsonStr, randomKey);

            //存储token至redis
            redisUtil.set(RedisKeyEnum.REDIS_KEY_USER_INFO.getKey() + redisUserKey,
                    token,
                    RedisKeyEnum.REDIS_KEY_USER_INFO.getExpireTime());

            return Result.success(userDto);
        }
    }

    public Result<?> getUserData(Long id) {
        User user = userMapper.selectById(id);
        UserVo2 userVo2 = new UserVo2();
        userVo2.setId(user.getId()).setUsername(user.getUsername()).setRoot(user.getRoot()).setName(user.getName());
        return Result.success(userVo2);
    }
}
